# -*- coding: utf-8 -*-
import time
import schedule
from utils.MysqlPool import MysqlPool
from utils.ddMessage import message
from utils.log import logger


def current_progress(success_count, total_counter):
    return round(float(success_count / total_counter) * 100, 1)


class SelectData:
    def __init__(self):
        self.total_counter_sql = "SELECT COUNT(1) FROM productdetail WHERE productID in (SELECT id FROM productinfo   WHERE classID = 'a6d8ef2f-ef44-11eb-a46c-00ffac4ac9fe');"
        self.success_count_sql = "SELECT COUNT(1) FROM productdetail WHERE `status` = 1 and productID in (SELECT id FROM productinfo   WHERE classID = 'a6d8ef2f-ef44-11eb-a46c-00ffac4ac9fe');"  # -- 爬取成功数量
        self.not_crawl_sql = "SELECT COUNT(1) FROM productdetail WHERE `status` is NULL and productID in (SELECT id FROM productinfo   WHERE classID = 'a6d8ef2f-ef44-11eb-a46c-00ffac4ac9fe');"  # -- 待爬取数量"

    def query(self, sql):
        with MysqlPool()as cur:
            cur.execute(sql)
            counter = cur.fetchall()[0][0]
            return counter

    def compute_speed(self):
        res1 = self.query(self.success_count_sql)
        start_time = time.time()
        res2 = self.query(self.success_count_sql)
        time.sleep(10)
        time_consuming = time.time() - start_time
        crawl_speed = round(float(res2 - res1) / time_consuming, 1)
        return crawl_speed

    def total_counter(self):
        logger.info('query total_counter')
        return self.query(self.total_counter_sql)

    def success_count(self):
        logger.info('query success_count')
        return self.query(self.success_count_sql)

    def not_crawl(self):
        logger.info('query not_crawl')
        return self.query(self.not_crawl_sql)

    def speed(self):
        logger.info('query speed')
        return self.compute_speed()

    def run(self):
        total_counter = self.total_counter()
        success_count = self.success_count()
        not_crawl_counter = self.not_crawl()
        speed = self.speed()
        speed_of_progress = current_progress(success_count, total_counter)
        logger.info('wait......')
        if speed == 0:
            while True:
                message('虫子挂了')
                time.sleep(1)
                if self.speed():
                    break
        res_desc = f"""
biocompare\n
当前任务：{total_counter}
当前爬取：{success_count}
待爬取数：{not_crawl_counter}
爬取速度：{speed}/s
当前进度：{speed_of_progress}%
        """
        logger.info(res_desc)

        return res_desc


if __name__ == '__main__':
    sd = SelectData()
    message(sd.run())

    # from datetime import datetime


    # def send_msg():
    #     sd = SelectData()
    #     message(sd.run())
    #     logger.info(f'{datetime.now()}')


    # schedule.every(60).minutes.do(send_msg)

    # while True:
    #     time.sleep(0.01)
    #     # logger.info(f'{datetime.now()}')

    #     schedule.run_pending()
